<!--
Date: 2025-08-13
Copyright (c) 2025 CAX Conversion Project
-->
<template>
  <div class="p-2 operator_main">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80px">
            <el-form-item label="算子名" prop="operatorName">
              <el-input v-model="queryParams.operatorName" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="算子实现" prop="algorithmRealize">
              <el-input v-model="queryParams.algorithmRealize" placeholder="请输入" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计算对象" prop="caculate">
              <el-cascader
                v-model="queryParams.caculate"
                :options="calculateObject"
                :props="typeProps"
                collapse-tags="true"
                max-collapse-tags="1"
                clearable
                placeholder="请选择"
              />
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-cascader
                v-model="queryParams.type"
                :options="operatorType"
                :props="typeProps"
                collapse-tags="true"
                max-collapse-tags="1"
                clearable
                placeholder="请选择"
              />
            </el-form-item>
            <el-form-item style="padding-left: 80px">
              <el-button type="primary" icon="search" @click="doQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" type="primary" plain icon="Plus" @click="handleVisible('add')">新增算子</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"> 删除 </el-button>
            </el-col> -->

          <right-toolbar v-model:showSearch="showSearch" @query-table="doQuery"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-if="showTable"
        v-loading="loading"
        :data="operatorList"
        :header-cell-class-name="handleHeaderClass"
        @selection-change="handleSelectionChange"
        @header-click="handleHeaderCLick"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="算子名" align="center" prop="operatorName" width="250" show-overflow-tooltip fixed="left" />
        <el-table-column label="算子实现" align="center" prop="algorithmRealize" width="300" show-overflow-tooltip />
        <el-table-column label="类型" align="center" prop="type" width="300" show-overflow-tooltip />
        <el-table-column label="计算对象" align="center" prop="coculate" width="300" show-overflow-tooltip />
        <el-table-column label="已使用" align="center" prop="used" />
        <el-table-column label="操作" width="210" fixed="right">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button size="small" link type="primary" icon="EditPen" @click="handleVisible('edit', scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="备注" placement="top">
              <el-button size="small" link type="primary" icon="Document" @click="handleVisible('view', scope.row)">备注</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <el-pagination
          v-show="total > 0"
          layout="prev, pager, next,jumper"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
  <!-- 新增/修改算法组件 -->
  <AddOperator :operatorType="operatorType" :addVisible="addVisible" :rowData="currentRow" @close="handleClose" v-if="addVisible" />
  <OperatorRemarkView :operatorRemarkVisible="operatorRemarkVisible" :rowData="currentRow" @close="handleClose" />
</template>
    
<script setup name="algorithmLibrary">
import AddOperator from './component/AddOperator.vue';
import { calculateObject } from './algorithmLibrary.js';
import OperatorRemarkView from './component/OperatorRemarkView.vue';
import { getOperatorList, deleteOperator, getDictValues } from '@/api/algorithmLibrary';
// 数据定义
const typeProps = { multiple: true };
const showTable = ref(true);
const loading = ref(false);
const operatorType = ref([]);
// 算法列表
const operatorList = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  operatorName: '',
  algorithmRealize: '',
  caculate: '',
  type: '',
  isAsc: 'descending'
});
const total = ref(0);
const showSearch = ref(true);
const resultList = ref([]);
//  新增算子
const addVisible = ref(false);
const currentRow = ref();
const operatorRemarkVisible = ref(false);

const { proxy } = getCurrentInstance();

// 查询类型字典
getDictValues({ dictType: 'operator_type', dictLabel: 'type' }).then((res) => {
  if (res.data.dictValue) {
    operatorType.value = JSON.parse(res.data.dictValue) || [];
  }
});
//删除
const handleDelete = async (row) => {
  await proxy?.$modal.confirm('是否确认删除该数据项?');
  deleteOperator(row).then((res) => {
    if (res?.code === 200) {
      proxy?.$modal.msgSuccess('删除成功');
      doQuery();
    }
  });
};

const handleHeaderClass = () => {};
const handleSelectionChange = () => {};
const handleHeaderCLick = () => {};
const handleQuery = () => {};
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    operatorName: '',
    algorithmRealize: '',
    caculate: '',
    type: '',
    isAsc: 'descending'
  };
  doQuery();
};

// 打开弹窗方法
const handleVisible = (param, data) => {
  if (param != 'add') {
    const valueData = resultList.value.filter((el) => {
      return el._id === data.id;
    });
    currentRow.value = valueData[0];
  }

  switch (param) {
    case 'add': {
      currentRow.value = null;
      addVisible.value = true;
      break;
    }
    case 'edit': {
      addVisible.value = true;
      break;
    }
    case 'view': {
      operatorRemarkVisible.value = true;
      break;
    }
  }
};
// 关闭弹窗
const handleClose = (param) => {
  const { type, data } = param;
  switch (type) {
    case 'add': {
      if (data?.type === 'refesh') {
        doQuery();
      }
      addVisible.value = false;
      break;
    }
    case 'view': {
      operatorRemarkVisible.value = false;
      break;
    }
  }
};
const handleCurrentChange = (number) => {
  queryParams.value.pageNum = number;
  doQuery();
};
// 查询参数组装
const processQuery = () => {
  if (queryParams.value.caculate && queryParams.value.caculate.length > 0) {
    queryParams.value.calculateObjects = queryParams.value.caculate.map((el) => {
      return { objectType: el[0], objectName: el[1] };
    });
  }
  if (queryParams.value.type && queryParams.value.type.length > 0) {
    queryParams.value.typeList = queryParams.value.type.map((el) => {
      return { applicationType: el[0], materialType: el[1], algorithmType: el[2] };
    });
  }
  return queryParams.value;
};
const doQuery = () => {
  loading.value = true;
  const params = processQuery();
  getOperatorList(params).then(async (res) => {
    loading.value = false;
    // 处理数据
    resultList.value = res?.rows || [];
    const resultData = res?.rows || [];
    let returnArr = [];
    total.value = res?.total;
    operatorList.value = [];
    await resultData.forEach(async (el) => {
      const row = {};
      row.id = el._id;
      row.operatorName = el.operatorName;
      row.algorithmRealize = el.algorithmRealize;
      // row.type = `${el.applicationType} / ${el.materialType ? el.materialType : ''} / ${el.algorithmType}`;
      row.type = coverData(el.applicationType, el.materialType, el.algorithmType);
      const coculateObj = el.calculateObjects || [];
      let coculatestr = '';
      await coculateObj.forEach((item) => {
        coculatestr += item.objectName ? `${item.objectType} / ${item.objectName},` : `${item.objectType},`;
      });
      row.coculate = coculatestr.slice(0, coculatestr.length - 1);
      row.used = el.used ? '是' : '否';
      row.operatorDescription = el.operatorDescription;
      returnArr.push(row);
    });
    operatorList.value = returnArr;
  });
};
const coverData = (applicationType, materialType, algorithmType) => {
  let returnStr = '';
  const orgArr = operatorType.value;
  let materialTypeArr = [];
  let algorithmTypeArr = [];
  for (let i = 0; i < orgArr.length; i++) {
    if (orgArr[i].value === applicationType) {
      returnStr = `${orgArr[i].label}`;
      materialTypeArr = orgArr[i].children;
      break;
    }
  }
  for (let j = 0; j < materialTypeArr.length; j++) {
    if (materialTypeArr[j].value === materialType) {
      returnStr = `${returnStr} / ${materialTypeArr[j].label}`;
      algorithmTypeArr = materialTypeArr[j].children;
      break;
    }
  }
  for (let k = 0; k < algorithmTypeArr.length; k++) {
    if (algorithmTypeArr[k].value === algorithmType) {
      returnStr = `${returnStr} / ${algorithmTypeArr[k].label}`;
      break;
    }
  }
  return returnStr;
};

onMounted(() => {
  doQuery();
});
// onBeforeMount(() => {
//   // 查询类型字典
//   getDictValues({ dictType: 'operator_type', dictLabel: 'type' }).then((res) => {
//     if (res.data.dictValue) {
//       operatorType.value = JSON.parse(res.data.dictValue) || [];
//     }
//   });
// });
</script>
  <style lang="scss" scoped>
.operator_main {
  height: calc(100vh - 84px);
  overflow: auto;
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
:deep(.el-upload) {
  display: block;
}
</style>